<template>
    <view class="content">
        <button class="upload-btn" @click="chooseFile">选择Excel文件</button>
        <!-- <view class="result" v-if="fileData">
            <text>文件内容：</text>
            <scroll-view scroll-y class="data-preview">
                <text>{{ JSON.stringify(fileData, null, 2) }}</text>
            </scroll-view>
        </view> -->
    </view>
</template>

<script>
import * as XLSX from 'xlsx';
import { data } from '../../utils/data.js';
export default {
    data() {
        return {
            fileData: null
        };
    },
    methods: {
        // 选择文件方法
        chooseFile() {
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = '.xlsx,.xls';

            input.onchange = (e) => {
                const file = e.target.files[0];
                if (!file) return;

                const reader = new FileReader();

                reader.onload = (e) => {
                    try {
                        const workbook = XLSX.read(e.target.result, { type: 'array' });
                        const firstSheetName = workbook.SheetNames[0];
                        const worksheet = workbook.Sheets[firstSheetName];

                        // 处理合并单元格
                        if (worksheet['!merges']) {
                            worksheet['!merges'].forEach((merge) => {
                                const startCell = merge.s; // 合并区域的起始单元格
                                const endCell = merge.e; // 合并区域的结束单元格
                                const value = worksheet[XLSX.utils.encode_cell(startCell)]?.v; // 获取合并区域的值

                                // 将合并区域的值填充到所有合并的单元格中
                                for (let row = startCell.r; row <= endCell.r; row++) {
                                    for (let col = startCell.c; col <= endCell.c; col++) {
                                        const cellAddress = XLSX.utils.encode_cell({ r: row, c: col });
                                        if (!worksheet[cellAddress]) {
                                            worksheet[cellAddress] = { t: 's', v: value };
                                        }
                                    }
                                }
                            });
                        }

                        // 转换为JSON数据
                        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1, defval: '' });

                        // 获取表头
                        const headers = jsonData[0];
                        // 将后续每行数据转换为对象
                        const dataObjects = jsonData.slice(1).map(row => {
                            const obj = {};
                            headers.forEach((header, index) => {
                                obj[header] = row[index];
                            });
                            return obj;
                        });

                        // 更新数据
                        this.fileData = dataObjects;
                        console.log(this.fileData);
                        // 显示成功提示
                        uni.showToast({
                            title: '文件读取成功',
                            icon: 'success'
                        });
                        // 遍历fileData，把对应的数据存储到data数组里面
                        for (let i = 0; i < this.fileData.length; i++) {
                            data.requireList[i].first = this.fileData[i]['培训（考试）前资历要求'];
                            data.requireList[i].second = this.fileData[i]['岗位适任培训要求'];
                            data.requireList[i].third = this.fileData[i]['适任考试要求'];
                            data.requireList[i].fourth = this.fileData[i]['考试后资历要求'];
                        }
                        // 先清除本地的数据
                        uni.removeStorageSync('StorageData');
                        // 把data存储到本地
                        uni.setStorageSync('StorageData', data);
                    } catch (error) {
                        console.error('Excel解析错误:', error);
                        uni.showToast({
                            title: '文件解析失败',
                            icon: 'none'
                        });
                    }
                };

                reader.onerror = () => {
                    uni.showToast({
                        title: '文件读取失败',
                        icon: 'none'
                    });
                };

                // 以二进制方式读取文件
                reader.readAsArrayBuffer(file);
            };

            // 触发文件选择
            input.click();
        }
    }
};
</script>

<style>
.content {
    padding: 20px;
}

.upload-btn {
    width: 200px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    background-color: #007AFF;
    color: #fff;
    border-radius: 4px;
    margin: 20px auto;
}

.result {
    margin-top: 20px;
}

.data-preview {
    height: 500px;
    border: 1px solid #eee;
    padding: 10px;
    margin-top: 10px;
    background-color: #f8f8f8;
}
</style>    